<template>
  <div v-loading="loading" style="margin-top: 20px">
    <el-table
      ref="multipleTableRef"
      row-key="id"
      default-expand-all
      :data="tableData"
      highlight-current-row
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <slot></slot>
    </el-table>
    <div style="padding: 10px 0; text-align: right" v-if="total > 0 ">
      <el-pagination
        background
        :page-size="per_page"
        :current-page="page"
        prev-text="上一页"
        next-text="下一页"
        :layout="layout || 'total, sizes, prev, pager, next'"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script setup lang="ts">
  import request from "../utils/request";
  import { onMounted, onUnmounted, ref, watch } from "vue";
  import emitter from "../utils/mitt";
  import { ElMessage } from "element-plus";

  let callback: any;
  const tableData = ref<any[]>([]);
  const loading = ref<boolean>(false);

  const page = ref<number>(1);
  const per_page = ref<number>(10);
  const total = ref<number>(0);
  const multipleTableRef = ref<any>()

  const props = defineProps({
    url: {
      type: String,
      default: "",
    },
    query: {
      type: Object,
      default: {},
    },
    reloadQuery: {
      type: Object,
      default: {},
    },
    method: {
      type: String,
      default: "post",
    },
    resListPath: {
      //处理后端返回的数据格式发生变化的情况，自己输入路径
      required: false,
      type: String,
    },
    layout: {
      required: false,
      type: String,
    },
  });
  const emits = defineEmits(["getSelectionVal", "tableLoaded", "requestCallback"]);

  onMounted(() => {
    getTableData();
    callback = emitter.on("search", () => {
      handleCurrentChange(1);
    });
  });

  onUnmounted(() => {
    emitter.off("search", callback);
  });

  watch(props.reloadQuery, () => {
    reload();
  });

  const handleCurrentChange = (currentPage: number) => {
    page.value = currentPage;
    getTableData();
  };

  const handleSizeChange = (currentPerPage: number) => {
    per_page.value = currentPerPage;
    handleCurrentChange(1);
  };

  const reload = () => {
    handleCurrentChange(1);
  };

  const refresh = (isDelete?: boolean) => {
    // 最后一项查询上一页
    if (isDelete && tableData.value.length === 1) {
      page.value--;
    }
    getTableData();
  };

  function handleSelectionChange<T>(val: T) {
    emits("getSelectionVal", val);
  }
  
  function clearSelection() {
    multipleTableRef.value.clearSelection()
  }
  
  function toggleRowSelection(row: any, isSelect: boolean) {
    multipleTableRef.value.toggleRowSelection(row, isSelect)
  }

  const getTableData = () => {
    if (!props.url || props.url == "url") {
      ElMessage.error("请传入请求地址");
      return;
    }
    loading.value = true;
    tableData.value = []
    let config: { url: string; method: string; data?: any; params?: any } = {
      url: props.url,
      method: props.method,
      data: {
        pageNum: page.value,
        pageSize: per_page.value,
        ...props.query,
        ...props.reloadQuery,
      },
    };
    if (props.method == "get") {
      config.params = config.data;
    }
    
    request(config).then((res: any) => {
      loading.value = false;
      // 处理表单返回格式变更
      if (props.resListPath) {
        if (props.resListPath === '.') {
          emits("requestCallback", res.data)
          emits("tableLoaded", { response: res.data.data });
          return tableData.value = res.data.data;
        }
        const list = props.resListPath.split(".");
        let table = res.data.data;
        let index = 0;
        for (const item of list) {
          table = table[item];
          if (index === list.length - 2) total.value = table.total; //找到最大path-1层，获取total值
          index++;
        }
        tableData.value = table;
      } else {
        tableData.value = res.data.data.list || [];
        total.value = res.data.data.total;
      }
      emits("requestCallback", res.data)
      emits("tableLoaded", { response: res.data.data });
    });
  };

  defineExpose({
    refresh,
    reload,
    tableData,
    clearSelection,
    toggleRowSelection
  });
</script>
